﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace KingTools.Utils
{
    public class ByteBuffer
    {
        /// <summary>
        ///     String 写入字节长度 + 字节内容
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="str"></param>
        public static void putString(MemoryStream stream, string str)
        {
            try
            {
                var writer = new BinaryWriter(stream);
                if (str == null || str.Length < 1)
                {
                    writer.Write((short) 0);
                }
                else
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(str);
                    writer.Write(IPAddress.HostToNetworkOrder((short) bytes.Length));
                    writer.Write(bytes);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}